package org.jeecg.modules.bobo.common.util;

import org.hibernate.annotations.Cache;
import org.jeecg.common.constant.CacheConstant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @program: jeecg-boot-parent
 * @description:
 * @author: 三千霜
 * @create: 2020-04-24 14:43
 */
@Component
public class IpUtil {

    private static String upyunUrl;

    private static String uploadType;

    public static String getUpyunUrl() {
        return upyunUrl;
    }
    @Value(value = "${jeecg.upyun.upyun_url}")
    public void setUpyunUrl(String upyunUrl) {
        if (!upyunUrl.endsWith("/")) {
            upyunUrl = upyunUrl.concat("/");
        }
        IpUtil.upyunUrl = upyunUrl;
    }

    public static String getUploadType() {
        return uploadType;
    }
    @Value(value="${jeecg.uploadType}")
    public void setUploadType(String uploadType) {
        IpUtil.uploadType = uploadType;
    }

    /**
     * 获取客户端访问ip
     * @author 三千霜
     * @date 2020/10/12 14:49
     * @param:
     * @Return java.lang.String
     * @throws

     */
    public static String getUserIpAddr() {
        HttpServletRequest request = getRequest();

        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        // ipAddress = this.getRequest().getRemoteAddr();

        return ipAddress;
    }

    public static HttpServletRequest getRequest() {
        //获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //从获取RequestAttributes中获取HttpServletRequest的信息
        return (HttpServletRequest) (requestAttributes != null ? requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST) : null);
    }

    /**
     * 获取服务器网址
     * @author 三千霜
     * @date 2020/7/26 16:06
     * @param: request
     * @Return java.lang.String
     * @throws

     */
//    @Cacheable(value = "website")
    public static String getWebsite(HttpServletRequest request,boolean getContextPath) {
        if (getContextPath){
            return request.getScheme()+ "://"+ request.getServerName()+":"+request.getServerPort()+request.getContextPath();
        }else{
            return request.getScheme()+ "://"+ request.getServerName()+":"+request.getServerPort();
        }
    }
    public static String getWebsite(boolean getContextPath) {
        HttpServletRequest request = getRequest();
        if (getContextPath){
            return request.getScheme()+ "://"+ request.getServerName()+":"+request.getServerPort()+request.getContextPath();
        }else{
            return request.getScheme()+ "://"+ request.getServerName()+":"+request.getServerPort();
        }
    }
    public static String getWebsite(HttpServletRequest request) {
        return getWebsite(request,false);
    }

    /**
     * 获取图片api绝对路径
     * @author 三千霜
     * @date 2020/8/11 9:57
     * @param: request
     * @Return java.lang.String
     * @throws

     */
    public static String getImgUrl(HttpServletRequest request,String img) {
        if (img.trim().length() == 0) {
            return "";
        }
        //判断是否为绝对网址
        if(isHttpUrl(img.trim())){
            return img.trim();
        }else{
            return getWebsite(request,true)+"/api/common/static/"+img.trim();
        }
    }
    public static String getImgUrl(String img) {
        HttpServletRequest request = getRequest();
        if (img.trim().length() == 0) {
            return "";
        }
        //判断是否为绝对网址
        if(isHttpUrl(img.trim())){
            return img.trim();
        }else{
            return getWebsite(request,true)+"/api/common/static/"+img.trim();
        }
    }
    /**
     * 获取图片静态资源绝对路径
     * @author 三千霜
     * @date 2020/8/11 9:57
     * @param: request
     * @Return java.lang.String
     * @throws

     */
    public static String getImgStaticUrl(HttpServletRequest request,String img) {

        if (img.trim().length() == 0) {
            return "";
        }
        img=img.trim();
        //判断是否为绝对网址
        if(isHttpUrl(img.trim())){
            return img.trim();
        }else{
            if (uploadType.equals("upyun")){
                if (!img.trim().startsWith("/")) {
                    img = upyunUrl.substring(1);
                }
                return upyunUrl+img;
            }else if (uploadType.equals("minio")){
                return "";
            }else if (uploadType.equals("alioss")){
                return "";
            }else{
                return getWebsite(request,true)+"/"+img.trim();
            }



        }
    }
    public static String getImgStaticUrl(String img) {
        HttpServletRequest request = getRequest();
        if (img.trim().length() == 0) {
            return "";
        }
        //判断是否为绝对网址
        if(isHttpUrl(img.trim())){
            return img.trim();
        }else{
            if (uploadType.equals("upyun")){
                return upyunUrl+img.trim();
            }else if (uploadType.equals("minio")){
                return "";
            }else if (uploadType.equals("alioss")){
                return "";
            }else{
                return getWebsite(request,true)+"/"+img.trim();
            }

        }
    }
    /**
     * 判断字符串是否为URL
     * @param urls 需要判断的String类型url
     * @return true:是URL；false:不是URL
     */
    public static boolean isHttpUrl(String urls) {
        boolean isurl = false;
        //设置正则表达式
        String regex = "(((https|http)?://)?([a-z0-9]+[.])|(www.))"
                + "\\w+[.|\\/]([a-z0-9]{0,})?[[.]([a-z0-9]{0,})]+((/[\\S&&[^,;\u4E00-\u9FA5]]+)+)?([.][a-z0-9]{0,}+|/?)";
        //对比
        Pattern pat = Pattern.compile(regex.trim());
        Matcher mat = pat.matcher(urls.trim());
        //判断是否匹配
        isurl = mat.matches();
        if (isurl) {
            isurl = true;
        }
        return isurl;
    }

}
